import { Module } from "vuex";
import { UserState, RootState } from "./store.type";
import { localStorage } from "@/utils/storage";
import Api from "@/services";
const storeModule: Module<UserState, RootState> = {
    namespaced: true,
    state: {
        userInfo: (() => {
            const userInfo: any = localStorage.getItem("userInfo");
            return userInfo || null;
        })(),
        auth: (() => {
            const auth: any = localStorage.getItem("auth");
            return auth || null;
        })(),
        isSignIn: (() => {
            const auth: any = localStorage.getItem("auth");
            return !!(auth && auth.token && auth.refreshToken);
        })()
    },
    actions: {
        login({ commit, dispatch }, payload) {
            const { username, password } = payload;
            // console.log(payload);
            // commit(USER_LOGIN);
            return new Promise(async(resolve, reject) => {
                try {
                    // const formData = new FormData();
                    // formData.set("username", username);
                    // formData.set("password", password);
                    // formData.set("client_id", client.id);
                    // formData.set("client_secret", client.secret);
                    // formData.set("grant_type", "password");
                    const auth = await Api.server.login({
                        loader: false,
                        // data: formData
                        data: {
                            username,
                            password
                        }
                    });
                    if (auth.status !== 200 || auth.data.code !== 200) {
                        resolve(auth);
                        return;
                    }
                    const { data } = auth.data;
                    // console.log(data);
                    // const testToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsibWFuYWdlbWVudCJdLCJ1c2VyX25hbWUiOiIxODExMzEwODg4OCIsInNjb3BlIjpbIlJPTEVfQURNSU4iLCJST0xFX1VTRVIiLCJST0xFX0FQSSJdLCJleHAiOjE2MDk3Mzc2MzIsInVzZXIiOnsiaWQiOjEzNDU5MjY4OTEwNTEyODY1MjgsImRlcGFydG1lbnRJZCI6MTM0NTkyNTI2MDM4MTM4ODgwMCwidXNlcm5hbWUiOiIxODExMzEwODg4OCIsIm5hbWUiOiLpmYjpvpkiLCJ0ZWwiOiIxODExMzEwODg4OCIsInBvc2l0aW9uIjoi6ZmI6b6ZIiwidG9rZW4iOm51bGx9LCJqdGkiOiI3M2EwMWRlNS1mZmQzLTRmNzktOWMzMi04MDUzZTllYzk4MDQiLCJjbGllbnRfaWQiOiJjMSJ9.NmDJnom6CXuNRQZRRaDUsjReS11n9xvcCcNQmoeHgKk";
                    commit("loginSuccess", {
                        token: data.token || "",
                        refreshToken: data.refreshToken || ""
                    });
                    const info = await dispatch("getInfo", data || {});
                    if (info.data.code !== 200) {
                        resolve(info);
                        return;
                    }
                    resolve(auth);
                } catch (e) {
                    reject(e);
                }
            });
        },
        getInfo({ commit }, payload) {
            // commit(USER_GETINFO);
            return new Promise(async(resolve, reject) => {
                try {
                    const response = {
                        data: {
                            user: payload,
                            code: 200
                        }
                    };
                    // const response = await Api.server.userInfo({
                    //     loader: false
                    // });
                    // console.log(response);
                    // if (response.data.code !== 0) {
                    //     resolve(response);
                    //     return;
                    // }
                    commit("setInfo", response.data.user);
                    resolve(response);
                } catch (e) {
                    console.log(e);
                    commit("logout");
                    reject(new Error("获取账户信息失败！"));
                }
            });
        },
        refreshToken({ state, commit }) {
            return new Promise(async(resolve, reject) => {
                try {
                    const { data: auth } = await Api.server.refreshToken({
                        data: {
                            refreshToken: state.auth.refreshToken || ""
                        }
                    });
                    commit("refreshToken", auth.data);
                    resolve(auth.data);
                } catch (e) {
                    reject(e);
                }
            });
        },
        logout({ commit }) {
            // commit(USER_LOGOUT);
            return new Promise(resolve => {
                commit("logout");
                resolve(true);
            });
        }
    },
    mutations: {
        loginSuccess(state, payload) {
            state.auth = payload;
            if (payload) {
                state.isSignIn = true;
            }
            localStorage.setItem("auth", state.auth);
        },
        setInfo(state, payload) {
            state.userInfo = payload;
            localStorage.setItem("userInfo", state.userInfo);
        },
        refreshToken(state, payload) {
            state.auth = payload;
            localStorage.setItem("auth", payload);
        },
        logout(state) {
            const userInfo = localStorage.getItem("userInfo");
            userInfo && localStorage.removeItem("userInfo");
            const auth = localStorage.getItem("auth");
            auth && localStorage.removeItem("auth");
            state.isSignIn = false;
        }
    }
};
export default storeModule;
